package com.zjjt.dc.tools.upload.file.action;

import cn.hutool.core.util.StrUtil;
import com.zjjt.dc.tools.upload.file.util.AliOssUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AliOssBucketUploadFileAction {
    private static Logger log = LoggerFactory.getLogger(AliOssBucketUploadFileAction.class);
    private String fileDir = "./download/";
    private String absoluteFileDir = "";
    private String webPath = "";
    private AliOssUtil ossUtil;

    public AliOssBucketUploadFileAction(String dir, String webPath, String ossName) {
        if (StrUtil.isNotEmpty(dir)) {
            this.fileDir = dir;
            this.absoluteFileDir = resolveFilePath(dir);
        }else{
            this.absoluteFileDir = resolveFilePath(this.fileDir);
        }
        if(StrUtil.isNotEmpty(webPath)){
            this.webPath = webPath;
        }
        this.ossUtil = AliOssUtil.newInstance(ossName);
    }

    /**
     * 解析文件路径，将相对路径转换为绝对路径
     *
     * @param filePath 输入的文件路径
     * @return 解析后的绝对路径
     */
    private String resolveFilePath(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            filePath = "./download/";
        }

        Path path = Paths.get(filePath);

        // 如果是相对路径，转换为基于当前工作目录的绝对路径
        if (!path.isAbsolute()) {
            path = Paths.get(System.getProperty("user.dir"), filePath).normalize();
        } else {
            path = path.normalize();
        }

        // 确保路径以分隔符结尾
        String pathStr = path.toString();
        if (!pathStr.endsWith(File.separator)) {
            pathStr += File.separator;
        }
        pathStr = pathStr.replace("\\", "/");

        return pathStr;
    }

    public Map<String, String> actionFiles(List<String> images) throws Exception {
        Map<String, String> result = new HashMap<>();
        for (String image : images) {
            String imagePath = image.substring(image.lastIndexOf("/"), image.length());
            try {
                File file = new File(absoluteFileDir + imagePath);
                if (file.exists()) {
                    Path path = Paths.get(fileDir + imagePath);
                    String fileName = file.getName();
                    byte[] fileBytes = Files.readAllBytes(path);
                    String contentType = Files.probeContentType(path);

                    // 使用自定义 MultipartFile 实现替代 CommonsMultipartFile 构造函数
                    MultipartFile multipartFile = new CustomMultipartFile(imagePath, fileName, contentType, fileBytes);

                    String uploadBack = ossUtil.upload(multipartFile, this.webPath);
                    result.put(image, uploadBack);
                } else {
                    log.error("文件不存在: {}", fileDir + imagePath);
                }
            } catch (IOException e) {
                log.error("上传文件失败: {}", imagePath, e);

            }
        }
        return result;
    }

    // 自定义 MultipartFile 实现类
    private static class CustomMultipartFile implements MultipartFile {
        private final String name;
        private final String originalFilename;
        private final String contentType;
        private final byte[] content;

        public CustomMultipartFile(String name, String originalFilename, String contentType, byte[] content) {
            this.name = name;
            this.originalFilename = originalFilename;
            this.contentType = contentType;
            this.content = content;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getOriginalFilename() {
            return originalFilename;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public boolean isEmpty() {
            return content == null || content.length == 0;
        }

        @Override
        public long getSize() {
            return content.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return content;
        }

        @Override
        public java.io.InputStream getInputStream() throws IOException {
            return new java.io.ByteArrayInputStream(content);
        }

        @Override
        public void transferTo(File dest) throws IOException, IllegalStateException {
            Files.write(dest.toPath(), content);
        }
    }
}